/*
Copyright (c) 2005-2008, CellAO Team

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the CellAO Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using AO.Core;
using AO.Core.Config;
using Cell.Core;
using ComponentAce.Compression.Libs.zlib;

namespace ZoneEngine
{
    /// <summary>
    /// 
    /// </summary>
    public class Client : ClientBase
    {
        #region Constructors

        /// <summary>
        /// 
        /// </summary>
        /// <param name="srvr"></param>
        public Client(Server srvr)
            : base(srvr)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        public Client()
            : base(null)
        {
        }

        #endregion

        #region Needed overrides

        /// <summary>
        /// 
        /// </summary>
        /// <param name="num_bytes"></param>
        protected override void OnReceive(int num_bytes)
        {
            byte[] packet = new byte[num_bytes];
            Array.Copy(m_readBuffer.Array, m_readBuffer.Offset, packet, 0, num_bytes);
            uint messageNumber = GetMessageNumber(packet);
            Parser newParser = new Parser();
            newParser.Parse(this, packet, messageNumber);
        }

        #endregion

        #region Misc overrides

        /// <summary>
        /// 
        /// </summary>
        /// <param name="packet"></param>
        public override void Send(byte[] packet)
        {
            base.Send(packet);
        }

        /// <summary>
        /// 
        /// </summary>
        public override void Cleanup()
        {
            base.Cleanup();
            //AH FINALLY, Man, get some NORMAL names (OnDisconnect maybe?).
            CharStatus.SetOffline(this.Character.characterId);
        }

        #endregion

        #region Our own stuff

        public Character Character = new Character(0, null);

        private NetworkStream m_netStream;

        private ZOutputStream m_zStream;

        /// <summary>
        /// 
        /// </summary>
        public NetworkStream NetStream
        {
            get
            {
                return m_netStream;
            }
            set
            {
                m_netStream = value;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public ZOutputStream CmpStream
        {
            get
            {
                return m_zStream;
            }
            set
            {
                m_zStream = value;
            }
        }

        /// <summary>
        /// Experimental - Check who is in the given radius
        /// </summary>
        /// <param name="Radius">RAdius</param>
        /// <returns></returns>
        public System.Collections.Generic.List<Client> GetClientsInRadius(float Radius)
        {
            System.Collections.Generic.List<Client> Clients = new System.Collections.Generic.List<Client>();
            //we're added ourselves, because we're included in the list too.
            //Clients.Add(this);
            foreach (Client cli in this.Server.Clients)
            {
                float DeltaX = cli.Character.coord.x - Character.coord.x;
                float DeltaY = cli.Character.coord.y - Character.coord.y;

                float DeltaRadius = (float)Math.Sqrt((double)((DeltaX * DeltaX) + (DeltaY + DeltaY)));

                if (DeltaRadius < Radius)
                {
                    Clients.Add(cli);
                }
            }
            return Clients;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="packet"></param>
        /// <returns></returns>
        protected uint GetMessageNumber(byte[] packet)
        {
            byte[] messageNumberArray = new byte[4];
            messageNumberArray[3] = packet[16];
            messageNumberArray[2] = packet[17];
            messageNumberArray[1] = packet[18];
            messageNumberArray[0] = packet[19];
            uint reply = BitConverter.ToUInt32(messageNumberArray, 0);
            return reply;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MsgCategory"></param>
        /// <param name="MsgNum"></param>
        /// <returns></returns>
        public bool SendFeedback(int MsgCategory, int MsgNum)
        {
            PacketWriter _writer = new PacketWriter();
            _writer.PushByte(0xDF);
            _writer.PushByte(0xDF);
            _writer.PushShort(10); /* Packet type */
            _writer.PushShort(1); /* ? */
            _writer.PushShort(0); /* Packet size (0 for now, PacketWriter takes care of it)*/
            _writer.PushInt(3086); /* Sender (our server ID)*/
            _writer.PushInt(Character.characterId); /* Receiver */
            _writer.PushInt(0x50544d19); /* Packet ID */
            _writer.PushIdentity(50000, Character.characterId); /* Affected identity */
            _writer.PushByte(1); /* ? */
            _writer.PushInt(0); /* ? */
            _writer.PushInt(MsgCategory); /* Message category ID */
            _writer.PushInt(MsgNum); /* message ID */
            byte[] reply = _writer.Finish();
            CmpStream.Write(reply, 0, reply.Length);
            CmpStream.Flush();
            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public bool SendChatText(string Text)
        {
            PacketWriter _writer = new PacketWriter();

            _writer.PushByte(0xDF); _writer.PushByte(0xDF);
            _writer.PushShort(10);
            _writer.PushShort(1);
            _writer.PushShort(0);
            _writer.PushInt(3086);
            _writer.PushInt(Character.characterId);
            _writer.PushInt(0x5F4B442A);
            _writer.PushIdentity(50000, Character.characterId);
            _writer.PushByte(0);
            _writer.PushShort((short)Text.Length);
            _writer.PushBytes(Encoding.ASCII.GetBytes(Text));
            _writer.PushShort(0x1000);
            _writer.PushInt(0);
            byte[] reply = _writer.Finish();
            CmpStream.Write(reply, 0, reply.Length);
            CmpStream.Flush();
            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="destination"></param>
        /// <param name="heading"></param>
        /// <param name="playfield"></param>
        /// <returns></returns>
        public bool Teleport(AOCoord destination, Quaternion heading, int playfield)
        {
            PacketWriter writer = new PacketWriter();
            // header starts
            writer.PushByte(0xDF); writer.PushByte(0xDF);
            writer.PushShort(10);
            writer.PushShort(1);
            writer.PushShort(0);
            writer.PushInt(3086);
            writer.PushInt(Character.characterId);
            writer.PushInt(0x43197D22);
            writer.PushIdentity(50000, Character.characterId);
            writer.PushByte(0);
            // Header ends
            writer.PushCoord(destination);
            writer.PushQuat(heading);
            writer.PushByte(97);
            writer.PushIdentity(51100, playfield);
            writer.PushInt(0);
            writer.PushInt(0);
            writer.PushIdentity(40016, playfield);
            writer.PushInt(0);
            writer.PushInt(0);
            writer.PushIdentity(100001, playfield);
            writer.PushInt(0);
            writer.PushInt(0);
            writer.PushInt(0);
            byte[] tpreply = writer.Finish();
            Misc.Announce.Playfield(this, tpreply);

            Character.stopMovement();
            Character.rawCoord = destination;
            Character.pf = playfield;
            Character.Purge(); // Purge character information to DB before client reconnect

            IPAddress tempIP;
            if (IPAddress.TryParse(ConfigReadWrite.Instance.CurrentConfig.ZoneIP, out tempIP) == false)
            {
                IPHostEntry zoneHost = Dns.GetHostEntry(ConfigReadWrite.Instance.CurrentConfig.ZoneIP);
                foreach (IPAddress ip in zoneHost.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        tempIP = ip;
                        break;
                    }
                }
            }
            int zoneIP = IPAddress.HostToNetworkOrder(BitConverter.ToInt32(tempIP.GetAddressBytes(), 0));
            short zonePort = Convert.ToInt16(ConfigReadWrite.Instance.CurrentConfig.ZonePort);

            PacketWriter writer2 = new PacketWriter();
            writer2.PushByte(0xDF); writer2.PushByte(0xDF);
            writer2.PushShort(1);
            writer2.PushShort(1);
            writer2.PushShort(0);
            writer2.PushInt(3086);
            writer2.PushInt(Character.characterId);
            writer2.PushInt(60);
            writer2.PushInt(zoneIP);
            writer2.PushShort(zonePort);
            byte[] connect = writer2.Finish();
            CmpStream.Write(connect, 0, connect.Length);
            CmpStream.Flush();
            return true;
        }

        #region Lua Hooks

        /// <summary>
        /// 
        /// </summary>
        /// <param name="a"></param>
        public void Print(string a)
        {
            SendChatText(a);
        }

        #endregion

        #endregion
    }
}
